package com.utils.excel;


import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import java.io.File;
import java.io.IOException;

public class ExcelHelper {

    private WritableWorkbook workbook;
    private WritableSheet sheet;

    public ExcelHelper(String filepath, String sheetName, int sheetIndex){
        File file = new File(filepath);
        if ( !file.exists() ){
            try {
                file.createNewFile();
                workbook = Workbook.createWorkbook(file);
                sheet = workbook.createSheet(sheetName, sheetIndex);
            } catch (IOException e) {
                e.printStackTrace();
                workbook = null;
                sheet = null;
                return;
            }
        }
    }

    public boolean insert(int line, String[] items){
        if (workbook == null || sheet == null){
            return false;
        }
        for(int i=0;i<items.length;i++){
            Label label = new Label(i, line, items[i]);
            try {
                sheet.addCell(label);
            } catch (WriteException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public boolean save(){
        if (workbook == null){
            return false;
        }
        try {
            workbook.write();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean close(){
        if (workbook == null){
            return false;
        }
        try {
            workbook.close();
        } catch (IOException | WriteException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean saveAndClose(){
        return save() && close();
    }
}
